# coding=utf-8
from gevent import monkey
monkey.patch_all()  # 打补丁，识别耗时操作，必须在requsets之前
from queue import Queue
from gevent.pool import Pool

import requests
from lxml import etree


class QB(object):
    def __init__(self):
        self.temp_url = "https://www.qiushibaike.com/hot/page/{}"
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36"}
        self.queue = Queue()
        self.total_request_num = 0
        self.total_response_num = 0
        self.pool = Pool(4)
        self.is_running = True

    def get_url_list(self):
        for i in range(1, 14):
            self.queue.put(self.temp_url.format(i))
            self.total_request_num += 1

    def parse_url(self, url):
        response = requests.get(url, headers=self.headers)
        print(response)
        return response.content.decode()

    def get_content_list(self, html_str):
        html = etree.HTML(html_str)
        div_list = html.xpath("//div[@id='content-left']/div")
        content_list = []
        for div in div_list:
            item = {}
            item["user_name"] = div.xpath(".//h2/text()")[0].strip()
            item["content"] = [i.strip() for i in div.xpath(".//div[@class='content']/span/text()")]
            content_list.append(item)
        return content_list

    def save_content_list(self,content_list):
        for content in content_list:
            print(content)
        pass

    def _execute_request_content_save(self):
        """请求获取数据"""
        url = self.queue.get()
        # 获取数据
        html_str = self.parse_url(url)
        # 提取数据
        content_list = self.get_content_list(html_str)
        self.save_content_list(content_list)
        self.total_response_num += 1

    def _callback(self, temp):
        """回调，继续执行请求获取数据"""
        if self.is_running:
            self.pool.apply_async(self._execute_request_content_save, callback=self._callback)

    def run(self):
        # url列表
        self.get_url_list()
        # 遍历发送请求，获取数据
        self.pool.apply_async(self._execute_request_content_save, callback=self._callback)
        while True:
            if self.total_response_num >= self.total_request_num:
                self.is_running = False
                break

        self.pool.close()  # 关闭线程池，防止新的线程开启


if __name__ == '__main__':
    qb = QB()
    qb.run()